package com.google.code.swingonfire.image;

import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.util.Map;

import javax.swing.SwingUtilities;

public class ComponentBufferImageProvider extends ComponentBasedImageProvider
{

    /**
     * Creates an image provider, that returns a rendering of the specified component
     * 
     * @param component the component
     * @param transparent true if transparent
     */
    public ComponentBufferImageProvider(Component component, boolean transparent)
    {
        super(component, transparent);
    }

    /**
     * Creates an image provider, that returns a rendering of the specified component
     * 
     * @param component the component
     * @param transparent true if transparent
     * @param updateAfter a timespan in seconds - the image will be automatically updated, if it hasn't been access for
     *            the specified time. Specify updateAfter <= 0 to update the image each time it is accessed, specify
     *            updateAfter = Double.NaN to disable auto update
     */
    public ComponentBufferImageProvider(Component component, boolean transparent, double updateAfter)
    {
        super(component, transparent, updateAfter);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void drawImage(Graphics2D g, int width, int height)
    {
        Component component = getComponent();
        boolean visible = component.isVisible();

        // FIXME: ok, here comes a hard one: if the image is transparent, then the LCD Subpixle-Sampling
        // setting differs from the system one, which will lead to not so nice font rendering

        // FIXME: this works only in windows

        // FIXME: antialising should only be turned off, if LCD subsampling is used (ON will disable subsampling)
        Toolkit tk = Toolkit.getDefaultToolkit();
        Map map = (Map) (tk.getDesktopProperty("awt.font.desktophints"));
        if (map != null)
        {
            g.addRenderingHints(map);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        }

        if (SwingUtilities.getWindowAncestor(component) == null)
        {
            throw new NullPointerException("Component does not belong to any window");
        }

        component.setVisible(true);
        component.paint(g);
        component.setVisible(visible);

    }
}
